﻿using Newtonsoft.Json;
using System.Net.Http;
using System.Text;


namespace StockUI;

public  class HttpClientHelper
{
    private readonly HttpClient _httpClient;
    private string _baseIPAddress;

    public HttpClientHelper()
    {
        _httpClient = new HttpClient();
    }

    public HttpClientHelper(string ipaddress = "", bool hideHttps = false)
    {
        this._baseIPAddress = ipaddress;

        if (hideHttps)
        {
            var handler = new HttpClientHandler();
            // 忽略证书验证
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
            _httpClient = new HttpClient(handler) { BaseAddress = new Uri(_baseIPAddress) };
        }
        else
        {
            _httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
        }
    }
    /// <summary>
    /// Get请求数据 返回序列化后的对象
    /// <para>最终以url参数的方式提交</para>
    /// </summary>
    /// <param name="parameters">参数字典</param>
    /// <param name="requestUri">例如/api/Files/UploadFile</param>
    /// <returns>实体对象</returns>
    public  T Get<T>(Dictionary<string, string> parameters, string requestUri) where T : class
    {
        string jsonString = Get(parameters, requestUri);
        if (string.IsNullOrEmpty(jsonString))
            return null;

        return JsonConvert.DeserializeObject<T>(jsonString);
    }
    /// <summary>同步GET请求</summary>
    /// <param name="url"></param>
    /// <param name="headers"></param>
    /// <param name="timeout">请求响应超时时间，单位/s(默认100秒)</param>
    /// <returns></returns>
    public string HttpGet(string url, Dictionary<string, string> headers = null, int timeout = 0)
    {
        if (headers != null)
        {
            foreach (KeyValuePair<string, string> header in headers)
            {
                _httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
        }
        if (timeout > 0)
        {
            _httpClient.Timeout = new TimeSpan(0, 0, timeout);
        }
        var result = _httpClient.GetAsync(ConcatURL(url));
        Byte[] resultBytes = result.Result.Content.ReadAsByteArrayAsync().Result;
        return Encoding.UTF8.GetString(resultBytes);
    }

    private string Post(string requestUrl, HttpContent content)
    {
        var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
        Byte[] resultBytes = result.Result.Content.ReadAsByteArrayAsync().Result;
        return Encoding.UTF8.GetString(resultBytes);
    }
    /// <summary>
    /// Get请求数据 返回字符串
    /// <para>最终以url参数的方式提交</para>
    /// </summary>
    /// <param name="parameters">参数字典,可为空</param>
    /// <param name="requestUri">例如/api/Files/UploadFile</param>
    /// <returns></returns>
    public  string Get(Dictionary<string, string> parameters, string requestUri)
    {
        if (parameters != null)
        {
            var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
            requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
        }
        else
        {
            requestUri = ConcatURL(requestUri);
        }

        var result = _httpClient.GetStringAsync(requestUri);
        return result.Result;
    }
    /// <summary>把请求的URL相对路径组合成绝对路径</summary>
    private string ConcatURL(string requestUrl)
    {
        if (_httpClient.BaseAddress!=null)
        {
            return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
        }
        return new Uri(requestUrl).OriginalString;
    }
}
